<template>
  <div class="container">
    <div class="userinfo">
      <view class="userinfo-avatar">
        <open-data  type="userAvatarUrl"></open-data>
      </view>
      <open-data type="userNickName"></open-data>
    </div>
    <year-progress></year-progress>
    <!-- 需要使用 button 来授权登录 -->
    <button v-if="canIUse && !userinfo.openId" open-type="getUserInfo" @getuserinfo="doLogin">授权登录</button>
    <view v-if="!canIUse" class="sj">请升级微信版本！</view>
    <button v-if='userinfo.openId' class="btn" @click="scanBook">添加图书</button>
  </div>
</template>

<script>
import YearProgress from '@/components/YearProgress'
import qcloud from 'wafer2-client-sdk'
import { showSuccess, showModal, post } from '@/util'
import config from '@/config.js'
export default {
  data () {
    return {
      canIUse: wx.canIUse('button.open-type.getUserInfo'),
      userinfo: {}
    }
  },
  components: {
    YearProgress
  },
  methods: {
    async addBook (isbn) {
      const res = await post('/weapp/addbook', {
        isbn,
        openid: this.userinfo.openId
      })
      showModal('添加成功', `${res.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        success: res => {
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },
    doLogin () {
      // 首次登录
      // 设置登录地址
      qcloud.setLoginUrl(config.loginUrl)
      qcloud.login({
        success: res => {
          showSuccess('登录成功')
          this.userinfo = res
        },
        fail: err => {
          console.error(err)
          showModal('登录错误', err.message)
        }
      })
    }
  },
  onShow () {
    const session = qcloud.Session.get()
    if (session) {
      this.userinfo = session.userinfo
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  padding: 0 30rpx;
  .userinfo {
    margin-top: 100rpx;
    position: relative;
    height: 320rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    .userinfo-avatar {
      overflow:hidden;
      display: block;
      width: 160rpx;
      height: 160rpx;
      margin: 20rpx;
      margin-top: 50rpx;
      border-radius: 50%;
      border: 2px solid #fff;
      box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
    }
  }
  .sj {
    text-align: center;
    margin-top: 10px;
    color: #EA5A49;
    font-size: 18px;
  }
}
</style>
